import { createRouter, createWebHashHistory } from 'vue-router'
import { Cookie } from '@wattjs/network'
import store from '@/store'
import Layout from '@/layout/Index'
import { pageRoutes, appRoutes } from './routes'
import { isArray } from '@/utils/api'
import { ticketLogin, getMenuByAppId } from '@/api/user.model'

const isProd = process.env.NODE_ENV === 'production'
const routes = [
  {
    path: '/',
    name: 'index',
    component: Layout,
    children: [
      ...pageRoutes
    ]
  },
  ...appRoutes
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// 添加服务端路由
const addPageRoutes = (data) => {
  return new Promise(resolve => {
    data.forEach(async item => {
      const { children, path, name } = item
      if (children) await addPageRoutes(item.children)
      else {
        const componentName = path.split('/').map((ret, i) => i ? (ret.charAt(0).toUpperCase() + ret.slice(1)) : ret).join('')
        router.addRoute('index', {
          path,
          name: componentName,
          meta: { tag: true, title: name },
          component: () => import(/* webpackChunkName: "[request]" */`../views${path}/index.vue`)
        })
      }
    })
    resolve()
  })
}

let addRoute = false
router.beforeEach(async (to, from, next) => {
  if (to.query.ticket) {
    const DOMAIN = window.location.host
    const { uid, nickname: username, token, tokenExpired } = await ticketLogin.send({ ticket: to.query.ticket, domain: DOMAIN }) || {}
    if (uid && username && token && tokenExpired) {
      Cookie.set('OP_ID', uid, { expires: new Date(tokenExpired), domain: DOMAIN })
      Cookie.set('OP_NAME', username, { expires: new Date(tokenExpired), domain: DOMAIN })
      Cookie.set(process.env.VUE_APP_XSRF_HEADER, token, { expires: new Date(tokenExpired), domain: DOMAIN })
      store.commit('setUserInfo', { uid, username })
      next({ name: to.name, replace: true })
    } else {
      next({ name: 'error', query: { message: '登录失败，请稍后再试' } })
    }
    return
  }
  const ignores = ['login', 'error', 'noauth']
  if (!ignores.includes(to.name)) {
    // login
    if (!Cookie.get(process.env.VUE_APP_XSRF_HEADER)) {
      // 统一登录入口
      if (process.env.VUE_APP_LOGIN_URL) window.location.replace(`${process.env.VUE_APP_LOGIN_URL}?fromUrl=${encodeURIComponent(window.location.href)}`)
      else next({ name: 'login' })
      return
    } else if (!store.state.menuAuth.length) {
      // 根据权限查菜单
      const { menuTree, permissions } = await getMenuByAppId.send({ app_id: process.env.VUE_APP_APP_ID }) || {}
      if (isArray(menuTree) && menuTree.length) {
        store.commit('setMenuAuth', menuTree)
        store.commit('setPermission', permissions) // permission
        await addPageRoutes(menuTree)
        // 无权限
        router.addRoute('index', {
          path: '/:pathMatch(.*)',
          redirect: '/noauth'
        })
        addRoute = true
      }
      store.commit('setTagNaves', [])
    } else if (!addRoute && store.state.menuAuth.length) {
      await addPageRoutes(store.state.menuAuth)
      // 无权限
      router.addRoute('index', {
        path: '/:pathMatch(.*)',
        redirect: '/noauth'
      })
      addRoute = true
      if (to.path !== '/') next({ ...to, replace: true })
    }
  } if (to.name === 'login' && Cookie.get(process.env.VUE_APP_XSRF_HEADER)) {
    next({ name: 'dashboard' })
    return
  }
  next()
})

router.afterEach((to) => {
  if (to.fullPath && isProd) {
    window._hmt.push(['_setAutoPageview', false])
    window._hmt.push(['_trackPageview', to.fullPath])
  }
})

export default router
